package cn.minhx.trigger.http;

import cn.minhx.api.IMarketTradeService;
import cn.minhx.api.dto.LockMarketPayOrderRequestDTO;
import cn.minhx.api.dto.LockMarketPayOrderResponseDTO;
import cn.minhx.api.response.Response;
import cn.minhx.domain.activity.model.entity.MarketProductEntity;
import cn.minhx.domain.activity.model.entity.TrialBalanceEntity;
import cn.minhx.domain.activity.model.valobj.GroupBuyActivityDiscountVO;
import cn.minhx.domain.activity.service.IGroupBuyService;
import cn.minhx.domain.trade.moedel.entity.MarketPayOrderEntity;
import cn.minhx.domain.trade.moedel.entity.PayActivityEntity;
import cn.minhx.domain.trade.moedel.entity.PayDiscountEntity;
import cn.minhx.domain.trade.moedel.entity.UserEntity;
import cn.minhx.domain.trade.moedel.valobj.GroupBuyProgressVO;
import cn.minhx.domain.trade.service.ITradeLockOrderService;
import cn.minhx.types.enums.ResponseCode;
import cn.minhx.types.exception.AppException;
import com.alibaba.fastjson2.JSON;
import jakarta.annotation.Resource;
import java.util.Objects;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 营销交易服务
 *
 * @author min
 */
@Slf4j
@RestController()
@CrossOrigin("*")
@RequestMapping("/api/v1/gbm/trade/")
public class MarketTradeController implements IMarketTradeService {

	@Resource
	private IGroupBuyService groupBuyService;

	@Resource
	private ITradeLockOrderService tradeLockOrderService;

	@Override
	public Response<LockMarketPayOrderResponseDTO> lockMarketPayOrder(
			LockMarketPayOrderRequestDTO lockMarketPayOrderRequestDTO) {
		try {
			// 参数
			String userId = lockMarketPayOrderRequestDTO.getUserId();
			String source = lockMarketPayOrderRequestDTO.getSource();
			String channel = lockMarketPayOrderRequestDTO.getChannel();
			String goodsId = lockMarketPayOrderRequestDTO.getGoodsId();
			Long activityId = lockMarketPayOrderRequestDTO.getActivityId();
			String outTradeNo = lockMarketPayOrderRequestDTO.getOutTradeNo();
			String teamId = lockMarketPayOrderRequestDTO.getTeamId();
			String notifyUrl = lockMarketPayOrderRequestDTO.getNotifyUrl();

			log.info("营销交易锁单:{} LockMarketPayOrderRequestDTO:{}", userId,
					JSON.toJSONString(lockMarketPayOrderRequestDTO));

			if (StringUtils.isBlank(userId) || StringUtils.isBlank(source) || StringUtils.isBlank(channel)
					|| StringUtils.isBlank(goodsId) || StringUtils.isBlank(goodsId) || StringUtils.isBlank(notifyUrl)
					|| null == activityId) {
				return Response.<LockMarketPayOrderResponseDTO>builder().code(ResponseCode.ILLEGAL_PARAMETER.getCode())
						.info(ResponseCode.ILLEGAL_PARAMETER.getInfo()).build();
			}

			// 查询 outTradeNo 是否已经存在交易记录
			MarketPayOrderEntity marketPayOrderEntity = tradeLockOrderService
					.queryNoPayMarketPayOrderByOutTradeNo(userId, outTradeNo);
			if (null != marketPayOrderEntity) {
				LockMarketPayOrderResponseDTO lockMarketPayOrderResponseDTO = LockMarketPayOrderResponseDTO.builder()
						.orderId(marketPayOrderEntity.getOrderId())
						.discountedPrice(marketPayOrderEntity.getDiscountedPrice())
						.tradeOrderStatus(marketPayOrderEntity.getTradeOrderStatusEnumVO().getCode()).build();

				log.info("交易锁单记录(存在):{} marketPayOrderEntity:{}", userId, JSON.toJSONString(marketPayOrderEntity));
				return Response.<LockMarketPayOrderResponseDTO>builder().code(ResponseCode.SUCCESS.getCode())
						.info(ResponseCode.SUCCESS.getInfo()).data(lockMarketPayOrderResponseDTO).build();
			}

			// 判断拼团锁单是否完成
			if (null != teamId) {
				GroupBuyProgressVO groupBuyProgressVO = tradeLockOrderService.queryGroupBuyProgress(teamId);
				if (null != groupBuyProgressVO
						&& Objects.equals(groupBuyProgressVO.getTargetCount(), groupBuyProgressVO.getLockCount())) {
					log.info("交易锁单拦截-拼单目标已达成:{} {}", userId, teamId);
					return Response.<LockMarketPayOrderResponseDTO>builder().code(ResponseCode.E0006.getCode())
							.info(ResponseCode.E0006.getInfo()).build();
				}
			}

			// 营销优惠试算
			TrialBalanceEntity trialBalanceEntity = groupBuyService.trail(MarketProductEntity.builder().userId(userId)
					.source(source).channel(channel).goodsId(goodsId).activityId(activityId).build());

			// 人群限定
			if (!trialBalanceEntity.getIsVisible() || !trialBalanceEntity.getIsEnable()) {
				return Response.<LockMarketPayOrderResponseDTO>builder().code(ResponseCode.E0007.getCode())
						.info(ResponseCode.E0007.getInfo()).build();
			}

			GroupBuyActivityDiscountVO groupBuyActivityDiscountVO = trialBalanceEntity.getGroupBuyActivityDiscountVO();

			// 锁单
			marketPayOrderEntity = tradeLockOrderService.lockMarketPayOrder(UserEntity.builder().userId(userId).build(),
					PayActivityEntity.builder().teamId(teamId).activityId(activityId)
							.activityName(groupBuyActivityDiscountVO.getActivityName())
							.startTime(groupBuyActivityDiscountVO.getStartTime())
							.endTime(groupBuyActivityDiscountVO.getEndTime())
							.targetCount(groupBuyActivityDiscountVO.getTarget()).build(),
					PayDiscountEntity.builder().source(source).channel(channel).goodsId(goodsId)
							.goodsName(trialBalanceEntity.getGoodsName())
							.originalPrice(trialBalanceEntity.getOriginalPrice())
							.discountedPrice(trialBalanceEntity.getDiscountedPrice()).outTradeNo(outTradeNo)
							.notifyUrl(notifyUrl).build());

			log.info("交易锁单记录(新):{} marketPayOrderEntity:{}", userId, JSON.toJSONString(marketPayOrderEntity));

			// 返回结果
			return Response.<LockMarketPayOrderResponseDTO>builder().code(ResponseCode.SUCCESS.getCode())
					.info(ResponseCode.SUCCESS.getInfo())
					.data(LockMarketPayOrderResponseDTO.builder().orderId(marketPayOrderEntity.getOrderId())
							.discountedPrice(marketPayOrderEntity.getDiscountedPrice())
							.tradeOrderStatus(marketPayOrderEntity.getTradeOrderStatusEnumVO().getCode()).build())
					.build();
		} catch (AppException e) {
			log.error("营销交易锁单业务异常:{} LockMarketPayOrderRequestDTO:{}", lockMarketPayOrderRequestDTO.getUserId(),
					JSON.toJSONString(lockMarketPayOrderRequestDTO), e);
			return Response.<LockMarketPayOrderResponseDTO>builder().code(e.getCode()).info(e.getInfo()).build();
		} catch (Exception e) {
			log.error("营销交易锁单服务失败:{} LockMarketPayOrderRequestDTO:{}", lockMarketPayOrderRequestDTO.getUserId(),
					JSON.toJSONString(lockMarketPayOrderRequestDTO), e);
			return Response.<LockMarketPayOrderResponseDTO>builder().code(ResponseCode.UN_ERROR.getCode())
					.info(ResponseCode.UN_ERROR.getInfo()).build();
		}
	}
}
